<template>
	<a-select show-search :show-arrow="false" v-bind='attr' :filter-option='false'
		:not-found-content='fetching ? undefined : null' :options='options' @search='search' @change='change'>
		<template v-if='fetching' #notFoundContent>
			<a-spin size="small" />
		</template>
	</a-select>
</template>
<script setup lang='ts'>
	import {
		ref
	} from 'vue';

	const { api, labelFieldName, valueFieldName, ...attr} = withDefaults(defineProps<{
	    api : (keword:string) => any[]|object,
        value:number|string,
	    placeholder : string,
	    labelFieldName : string,
	    valueFieldName : string
	}>(), {
	    labelFieldName : 'label',
	    valueFieldName : 'id'

	})

    const emit = defineEmits<{
        (e : 'update:value', keyword : string|number)
    }>()

	const fetching = ref(false)
	const options = ref < any[] > ([])

    function change(e) {
        emit('update:value', e)
    }

	async function search(keyword) {
        options.value.splice(0)
		fetching.value = true
		const rows = await api(keyword)
		fetching.value = false
		if(rows) {
		    if(Array.isArray(rows)) {
		        if(rows.length > 0) {
		            if(typeof rows[0] == 'object') {
		                rows.forEach(row => {
		                    options.value.push({
		                        value : row[valueFieldName],
		                        label : row[labelFieldName]
		                    })
		                })
		            }else {
		                options.value = rows.map(row => ({value : row, label : row}))
		            }
		        }
		    }else {
		        for(let k in rows) {
		            options.value.push({
		                value : k,
		                label : rows[k]
		            })
		        }
		    }


		}
	}
</script>
